/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hitechbangla.fctu.form;

import com.hitechbangla.fctu.base.GameScene;
import com.hitechbangla.fctu.base.aircraft.Aircraft;
import com.hitechbangla.fctu.utility.AircraftUtility;
import com.hitechbangla.fctu.utility.GeneralUtil;
import com.hitechbangla.fctu.utility.RecordedGame;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *
 * @author DebKanti ---> Ratan
 */
public class CommandAircraftNew extends javax.swing.JFrame {

    /**
     * Creates new form CommandAircraftNew
     */
    
    private GameScene gameScene;

    public CommandAircraftNew(GameScene gameScene) {
	initComponents();
	jTextFieldCommandNew.addKeyListener(new CommandKeyListener());
	jTextFieldCommandNew.requestFocusInWindow();
	this.gameScene = gameScene;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextFieldCommandNew = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTextFieldCommandNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldCommandNewActionPerformed(evt);
            }
        });

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Enter Aircraft  Command :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextFieldCommandNew, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(27, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jTextFieldCommandNew, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldCommandNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCommandNewActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldCommandNewActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
	/* Set the Nimbus look and feel */
	//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
	 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
	 */
	try {
	    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
		if ("Nimbus".equals(info.getName())) {
		    javax.swing.UIManager.setLookAndFeel(info.getClassName());
		    break;
		}
	    }
	} catch (ClassNotFoundException ex) {
	    java.util.logging.Logger.getLogger(CommandAircraftNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (InstantiationException ex) {
	    java.util.logging.Logger.getLogger(CommandAircraftNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (IllegalAccessException ex) {
	    java.util.logging.Logger.getLogger(CommandAircraftNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (javax.swing.UnsupportedLookAndFeelException ex) {
	    java.util.logging.Logger.getLogger(CommandAircraftNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	}
	//</editor-fold>

	/* Create and display the form */
	java.awt.EventQueue.invokeLater(new Runnable() {
	    public void run() {
		//new CommandAircraftNew().setVisible(true);
	    }
	});
    }
    
    class CommandKeyListener implements  KeyListener
    {	
	private String command;	
	private final Voice voice;
        
        public CommandKeyListener()
        {
            command = "";
	    
	    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	 
	    String voiceName = "kevin16";
	    VoiceManager voiceManager =  VoiceManager.getInstance();
	    voice = voiceManager.getVoice(voiceName);

	    if (voice == null) {
		//System.out.println("Voice not found.");
		System.exit(1);
	    }

	    voice.allocate();
	    voice.setRate(120);
	    voice.setPitch(100);
        }

        @Override
        public void keyTyped(KeyEvent e) 
        {
            
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            
        }

        @Override
        public void keyReleased(KeyEvent e) 
        {	    
            String keyPressed = String.valueOf(e.getKeyChar());           
            
            if(keyPressed.equals("\n"))
            {   
               Runnable task = new Runnable() {

		    @Override
		    public void run() {
			//throw new UnsupportedOperationException("Not supported yet.");
			if (AircraftUtility.compareWithCommandRegEx(command)) {
			    String callSignCommand = command.substring(0, 3);
//		    jTextAreaCommandLog.setText(callSignCommand +"\n");
//		    //System.out.println(callSignCommand);
			    boolean flagAircraftFound = false;
			    for (Aircraft aircraft : gameScene.airCraftList) {
				if (aircraft.getAircraftState().getCallSign().equals(callSignCommand)) {
				    voice.speak("Executing command " + command);
				    aircraft.executeCommand(command);
				    flagAircraftFound = true;
                                    GeneralUtil.UpdateCommand(gameScene, command);
				    
				    RecordedGame recordedGame = gameScene.HTBParent.getRecordedGame();
	    
				    if(recordedGame!=null)
				    {
					if(recordedGame.isRecordingStarted())
					{
					    recordedGame.storeGameScene(gameScene);
					}
				    }
				}
			    }

			    if (flagAircraftFound == false) {
				voice.speak("Disregard aircraft not found , Disregard aircraft not found");
			    }
			} else {
			    voice.speak("Disregard wrong command, Disregard wrong command");
			}

			command = "";
			jTextFieldCommandNew.setText("");
		    }
		};
	       Thread th = new Thread(task);
	       th.start();
                
            }
            else
            {
                command += keyPressed;
            }
            
            ////System.out.println("Current command: " + command);
        } // end of keyPressed 
        
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextFieldCommandNew;
    // End of variables declaration//GEN-END:variables
}
